<template>
  <el-drawer
    v-model="visible"
    title="导入报名信息"
    :mask-closable="false"
    :esc-to-close="false"
    :size="width >= 400 ? 400 : '100%'"
  >
    <el-form ref="formRef" :model="form" size="large" auto-label-width>
      <el-alert v-if="!form.disabled" type="success" style="margin-bottom: 15px">
        <template #default>
          请按照模板要求填写数据，填写完毕后，请先上传并进行解析。
          <el-link @click="downloadTemplate">
            <template #icon><icon :size="12" name="el-icon-Files" /></template>
            <template #default>下载模板</template>
          </el-link>
        </template>
      </el-alert>
      <fieldset>
        <legend>1.解析数据</legend>
        <div class="file-box">
          <el-upload
            drag
            :http-request="handleUpload"
            :limit="1"
            :file-list="uploadFile"
            accept=".xls, .xlsx, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              到拽到这上传 或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只接收.xls, .xlsx格式
              </div>
            </template>
          </el-upload>
        </div>
        <div v-if="dataResult.importKey">
          <div class="file-box">
            <el-space size="large">
              <el-statistic title="总计行数" :value="dataResult.totalRows" />
              <el-statistic title="正常行数" :value="dataResult.validRows" />
            </el-space>
          </div>
          <div class="file-box">
            <el-space size="large">
              <el-statistic title="已存在用户" :value="dataResult.duplicateUserRows" />
              <el-statistic title="已存在手机" :value="dataResult.duplicatePhoneRows" />
            </el-space>
          </div>
        </div>
      </fieldset>
      <fieldset>
        <legend>2.导入策略</legend>
        <el-form-item label="选手已存在" field="duplicateUser">
          <el-radio-group v-model="form.duplicateUser" type="button">
            <el-radio :label="1">跳过该行</el-radio>
            <el-radio :label="3">停止导入</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机已存在" field="duplicatePhone">
          <el-radio-group v-model="form.duplicatePhone" type="button">
            <el-radio :label="1">跳过该行</el-radio>
            <el-radio :label="3">停止导入</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="默认状态" field="defaultStatus">-->
<!--          <el-switch-->
<!--            v-model="form.defaultStatus"-->
<!--            :checked-value="1"-->
<!--            :unchecked-value="2"-->
<!--            checked-text="启用"-->
<!--            unchecked-text="禁用"-->
<!--            type="round"-->
<!--          />-->
<!--        </el-form-item>-->
      </fieldset>
    </el-form>
    <template #footer>
      <div style="position: absolute; bottom: 0; left: 0; right: 0; padding: 10px; text-align: right; border-top: 1px solid #e4e7ed;">
        <el-button @click="reset">取消导入</el-button>
        <el-button type="primary" @click="save">确认导入</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { type FormInstance, ElMessage } from 'element-plus'
import { useWindowSize } from '@vueuse/core'
import {
  downloadApplyImportTemplate,
  parseImportApply,
  importApply
} from '@/api/competition/apply'
import {useDownload} from '@/hooks/useDownload'
import {UploadFilled} from "@element-plus/icons-vue";

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const visible = ref(false)
const formRef = ref<FormInstance>()
const uploadFile = ref([])
const route = useRoute()
const form = reactive({
  competitionId: '',
  importKey: '',
  errorPolicy: 1,
  duplicateUser: 1,
  duplicatePhone: 1,
  defaultStatus: 1,
})
const resetForm = reactive({
  errorPolicy: 1,
  duplicateUser: 1,
  duplicatePhone: 1,
  defaultStatus: 1,
})

const dataResult = ref({
  importKey: '',
  totalRows: 0,
  validRows: 0,
  duplicateUserRows: 0,
  duplicatePhoneRows: 0,
})

// 重置
const reset = () => {
  formRef.value?.resetFields()
  dataResult.value.importKey = ''
  uploadFile.value = []
  // resetForm()
  visible.value = false
}

// 下载模板
const downloadTemplate = () => {
  useDownload(() => downloadApplyImportTemplate())
}

// 上传解析导入数据
const handleUpload = (options: any) => {
  const controller = new AbortController();
  (async function requestWrap() {
    const { onProgress, onError, onSuccess, file, name = 'file' } = options
    onProgress(20, options.file, {});
    const formData = new FormData()
    formData.append(name as string, file as Blob)
    try {
      const res = await parseImportApply(formData)
      dataResult.value = res
      ElMessage.success('上传解析成功')
      onSuccess(res)
    } catch (error) {
      onError(error)
    }
  })()
  return {
    abort() {
      controller.abort()
    },
  }
}

// 执行导入
const save = async () => {
  try {
    if (!dataResult.value.importKey) {
      ElMessage.warning('请先上传文件，解析导入数据')
      return false
    }
    form.importKey = dataResult.value.importKey
    form.competitionId = route.query.id
    const res = await importApply(form)
    ElMessage.success(`导入成功! 总条数${res.totalRows}，新增${res.insertRows}`)
    visible.value = false
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

// 打开
const onOpen = () => {
  reset()
  visible.value = true
}

defineExpose({ onOpen })
</script>

<style scoped lang="scss">
fieldset {
  padding: 15px 15px 0 15px;
  margin-bottom: 15px;
  border: 1px solid var(--color-neutral-3);
  border-radius: 3px;
}

fieldset legend {
  color: rgb(var(--gray-10));
  padding: 2px 5px 2px 5px;
  border: 1px solid var(--color-neutral-3);
  border-radius: 3px;
}

.file-box {
  margin-bottom: 20px;
  margin-left: 10px;
}
</style>
